<template>
	<view class="cart-container">
        <u-navbar
            title="购物车"
            title-color="#FFFFFF"
            :is-fixed="true"
            :is-back="false"
            :background="background"
            :border-bottom="false"
            >
        </u-navbar>
        <view class="cart-view">
            <mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="down" :up="upOptions">
            	<view class="no-catr">
            	    <u-empty v-if="!cartList.length" text="购物车是空的,赶快去购买吧" mode="data"></u-empty>
            	    <view class="go-login-btn" v-if="!user">
            	        <u-button type="error" class="btn"  size="medium" @click="handleLogin">登录/注册</u-button>
            	    </view>
            	</view>
                <view class="cart-list-view" v-if="cartList && cartList.length">
                        <view class="seller-view" v-for="(cart, index) in cartList" :key="index">
                            <view class="seller-item u-flex u-col-center">
                                <view class="seller-checbox-view" @click="handleCheckSeller(cart)" >
                                    <u-icon v-if="!cart.invalid" :color="cart.checked === 1 ? '#ff5000' : ''" size="38" :name="cart.checked === 1? 'xuanze' : 'choose'" custom-prefix="custom-icon"></u-icon>
                                    <u-icon v-else custom-prefix="custom-icon"></u-icon>
                                </view>
                                <view class="seller-name-view u-flex">
                                    <u-icon name="shop" custom-prefix="custom-icon" size="35"></u-icon>
                                    <view class="u-margin-left-10">{{cart.seller_name}}</view>
                                </view>
                            </view>
                            <u-swipe-action
                                :show="sku.show" :index="sku.sku_id"
                            	v-for="(sku, skuIndex) in cart.sku_list" :key="sku.sku_id"
                                :options="options" @click="click" v-if="showSwipe"
                            >
                                <view class="cart-list" :class="sku.invalid === 1 ? 'invalid' : ''" >
                                    <view v-if="sku.error_message" class="error-message u-m-t-10">{{ sku.error_message }}</view>
                                    <view class="cart-item u-flex u-col-center">
                                        <view v-if="sku.invalid === 1">
                                            <view class="goods-checbox-view">已失效</view>
                                            <!-- <view class="goods-checbox-view" @click="handleCheckSku(sku)">
                                                <u-icon :color="sku.checked === 1 ? '#FA3534' : ''" size="38" :name="sku.checked === 1 ? 'xuanze' : 'choose'" custom-prefix="custom-icon"></u-icon>
                                            </view> -->
                                        </view>
                                        <view v-else class="goods-checbox-view" @click="handleCheckSku(sku)">
                                            <u-icon :color="sku.checked === 1 ? '#ff5000' : ''" size="38" :name="sku.checked === 1 ? 'xuanze' : 'choose'" custom-prefix="custom-icon"></u-icon>
                                        </view>
                                        <view class="u-flex u-flex-1" style="padding-left: 10rpx;">
                                            <navigator :url="'/goods-module/goods?goods_id=' + sku.goods_id  + '&&sku_id=' + sku.sku_id" hover-class="none" class="goods-img-view">
                                                <u-image border-radius="10" width="180" height="180" :src="sku.goods_image"></u-image>
                                            </navigator>
                                            <view class="goods-info-view u-flex-1">
                                                <navigator :url="'/goods-module/goods?goods_id=' + sku.goods_id  + '&&sku_id=' + sku.sku_id" hover-class="none" class="u-line-2 goods-title">
                                                   {{sku.name}}
                                                </navigator>
                                                <view class="goods-spec-view" v-if="sku.spec_list">
                                                    <text class="goods-spec">{{sku.spec_list | formatterSkuSpec }}</text>
                                                </view>
                                                <view class="promotion-view" v-if="sku.promotion_tags && sku.promotion_tags.length">
                                                    <u-tag class="u-m-r-20" :text="tag" type="error" mode="plain" v-for="(tag, tagIndex) in sku.promotion_tags" :key="tagIndex" />
                                                </view>
                                                <view class="u-flex act-view" v-if="sku.single_list && sku.single_list.length" @click="handleChangeActivity(sku)">
                                                    <view class="u-flex-1">
                                                        <text class="act-item-title u-font-24">促销</text>
                                                        <text class="act-item-cont">{{ sku.promotion_title }}</text>
                                                    </view>
                                                    <view class="u-m-l-10">
                                                        <u-icon :name="showActivityActionsheet ? 'arrow-up' : 'arrow-down'" :size="20"></u-icon>
                                                    </view>
                                                </view>
                                                <view class="u-flex u-row-between u-m-t-10">
                                                    <custom-price :price="sku.purchase_price" :fontWeight="600" :size="33"></custom-price>
                                                    <view v-if="sku.invalid !== 1">
                                                        <u-number-box :min="1" :max="sku.enable_quantity" :value="sku.num"
                                                            @minus="handleBuyNum"
                                                            @blur="handleBuyNum"
                                                            @plus="handleBuyNum" :index="sku.sku_id" >
                                                        </u-number-box>
                                                    </view>
                                                </view>
                                            </view>
                                        </view>
                                    </view>
                                </view>
                            </u-swipe-action>
                        </view>
                </view>
            </mescroll-body>
        </view>
        <!-- 促销活动弹出层 -->
        <u-popup v-model="showActivityActionsheet" mode="center" width="500rpx" height="600rpx" closeable close-icon-size="20" border-radius="20">
            <view class="act-box-view">
                <view class="title u-text-center u-m-t-20">促销活动</view>
                <view class="title u-m-30">请选择要参与的促销活动:</view>
                <view class="u-m-30">
                    <view class="act-item-view u-m-b-30" v-for="(item, index) in activity_options" :key="index" @click="handleActivitySelect(item)">
                        <u-icon :color="item.is_check === 1 ? '#ff5000' : ''" size="36" :name="item.is_check === 1 ? 'xuanze' : 'choose'" custom-prefix="custom-icon"></u-icon>
                        <text class="u-m-l-10 u-font-30">{{ item.text }}</text>
                    </view>
                </view>
            </view>
        </u-popup>
        <view class="settlement" v-if="cartList.length !== 0">
            <view class="goods-checbox-view u-flex">
                <view class="u-flex" @click="handleCheckAll">
                    <u-icon :color="all_checked ? '#ff5000' : ''" size="38" :name="all_checked ? 'xuanze' : 'choose'" custom-prefix="custom-icon"></u-icon>
                    <text class="u-m-l-10">全选</text>
                </view>
                <text v-if="checkedCount" class="del-btn" @click="handleBatchDelete">删除已选</text>
            </view>
            <view class="u-flex">
                <view class="u-margin-right-20">
                    <view class="u-flex u-row-right">
                        <text>合计：</text>
                        <custom-price :price="totalPrice.total_price" :fontWeight="600"></custom-price>
                    </view>
                    <view class="u-flex u-font-24 u-row-right cash-back" v-if="totalPrice.cash_back">
                        <text>返现：</text>
                        <custom-price :price="totalPrice.cash_back" :size="24" :fontWeight="600"></custom-price>
                    </view>
                </view>
                <u-button shape="circle" size="medium" :custom-style="customStyle" @click="goSettlement">去结算</u-button>
            </view>
        </view>
        <u-no-network></u-no-network>
	</view>
</template>

<script>
    import * as API_Trade from '@/api/trade.js'
    import Cache,{Keys} from '@/utils/cache.js'
    import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js"
    import { RegExp } from '@/ui-utils/index.js'
	export default {
        mixins: [MescrollMixin],
		data() {
			return {
                buyNum: 1,
                cartList: [],
                skuList: [],
                totalPrice: {},
                user: Cache.getItem('user'),
                checkedCount: 0, //选中的商品数量
                allCount: 0, //所有商品数量
                options: [
                    {
                        text: '删除',
                        style: {
                            backgroundColor: '#ff5000'
                        }
                    }
                ],
                activity_options: [], //促销活动
                cur_sku_id: null, //当前选择的sku_id
                showActivityActionsheet: false, //是否显示促销活动
                customStyle: {
                    background: 'linear-gradient(145deg,#ff9000,#ff5000 77%)',
                    color: '#FFFFFF',
                    height: '80rpx'
                }, //自定义按钮样式
                networkType: '',//网络状态
                background: {
                    background: '#ff5000'
                },
                down: {
                    auto: false
                },
                upOptions: {
                    auto: false
                },
                showSwipe: true
			};
		},
        onLoad() {
            let $this = this
            //获取网络类型
            uni.getNetworkType({
                success(res) {
                    $this.networkType = res.networkType
                    if (res.networkType !== 'none') {
                        $this.user = Cache.getItem('user')
                        if ($this.user) {
                            // console.log("====onLoad====")
                            // $this.downCallback()
                        } else {
                            $this.cartList = []
                        }
                    }
                }
            })

            //监听退出登录消息
            uni.$on('logout',function(data){
                $this.user = null;
                $this.cartList = []
            })
        },
        onShow() {
            let $this = this
            $this.user = Cache.getItem('user')
            //监听网络状态变化
            uni.onNetworkStatusChange(res => {
                //监听到有网络并且第一次没有加载数据的情况下初始化数据
                if (res.isConnected && $this.networkType === 'none') {
                    if ($this.user) {
                        console.log("====onShow====")
                        $this.downCallback()
                    } else {
                        $this.cartList = []
                    }
                }
            })
            $this.downCallback()
        },
        computed: {
            // 是否全部选中
            all_checked() {
                return !!this.checkedCount && this.checkedCount === this.allCount
            },
        },
        methods: {
            //下拉刷新
            downCallback() {
                console.log("下拉刷新")
                if (this.user) {
                    this.getCartList()
                } else {
                    this.mescroll.endErr()
                }
            },
            //上拉加载
            upCallback(page) {
                this.mescroll.endErr()
            },
            //购买数量发生变化(避免使用@change事件带来的多次请求)
            handleBuyNum(e) {
                console.log('购买数量发生变化='+JSON.stringify(e))
                if (!RegExp.integer.test(e.value)) {
                     this.$u.toast('请输入大于0的正整数')
                     return
                }
                if (e.value > 2000000000 ) {
                    this.$u.toast('请输入小于2000000000的正整数')
                    return
                }
                this.buyNum = e.value
                API_Trade.updateSkuNum(e.index, this.buyNum).then(res => {
                    this.getCartList()
                })
            },
            //获取购物车数据
            getCartList() {
                console.log("=====获取购物车数据=====")
                if (!this.user) {
                    return;
                }
                API_Trade.getCarts('all').then(res => {
                    const { cart_list, total_price } = res
                    let _allCount = 0
                    let _checkedCount = 0
                    let _skuList = []
                    cart_list.forEach(cart => {
                        cart.sku_list.forEach(sku => {
                            sku.show = false
                            if (sku.invalid !== 1) _allCount += sku.num
                            if (sku.checked && sku.invalid !== 1) _checkedCount += sku.num
                            //处理促销活动
                            if (sku.single_list && sku.single_list.length) {
                                sku.promotion_title = this.selectedActivity(sku.single_list)
                            }
                        })
                        _skuList.push(...cart.sku_list)
                    })
                    this.cartList = cart_list
                    this.skuList = _skuList
                    this.totalPrice = total_price
                    this.allCount = _allCount
                    this.checkedCount = _checkedCount
                    setTimeout(() => {
                        this.mescroll.endSuccess(cart_list.length)
                    },300)
                })
            },
            //打开促销选择
            handleChangeActivity(sku) {
                console.log("=====handleChangeActivity=====")
                this.showActivityActionsheet = true
                const options = sku.single_list.map(item => ({
                    text: item.promotion_name,
                    seller_id: item.seller_id,//卖家id
                    //activity_id: item.activity_id,
                    promotion_id: item.promotion_id,
                    is_check: item.is_check,
                    promotion_type: item.promotion_type,
                    sku
                }))
                const no_act = sku.single_list.filter(item => item.is_check === 1)
                options.push({
                    text: '不参加活动',
                    is_check: no_act[0] ? 0 : 1,
                    sku
                })
                this.activity_options = options
                this.cur_sku_id = sku.sku_id
            },
            //确认促销选择
            handleActivitySelect(item) {
                console.log("=====确认促销选择=====")
                this.showActivityActionsheet = false
                const { sku_id ,seller_id} = item.sku
                if (item.text === '不参加活动') {
                    API_Trade.cleanPromotion(sku_id).then(() => {this.getCartList()})
                } else {
                    const { promotion_type, promotion_id } = item
                    const params = {
                        seller_id,
                        sku_id,
                        //activity_id,
                        promotion_id,
                        promotion_type
                    }
                    API_Trade.changeActivity(params).then(()=>{this.getCartList()})
                }
            },
            //展示已选择促销
            selectedActivity(list) {
                console.log("=====selectedActivity=====")
                const _list = list.filter(item => item.is_check === 1)
                if (_list[0]) {
                    return _list[0].title
                }
                return '不参加活动'
            },
            //去结算
            goSettlement() {
                if(!this.checkedCount) {
                    this.$u.toast('您还没有选中商品哦~')
                } else {
                    uni.navigateTo({
                        url: '/order-module/checkout/checkout'
                    })
                }
            },
            //勾选、取消勾选商品（点击店铺名称）
            handleCheckSeller(cart){
                console.log("=====handleCheckSeller=====")
                uni.showLoading({title: '加载中',mask:true});
                const checked = cart.checked ? 0 : 1
                API_Trade.updateSellerChecked(cart.seller_id, checked).then(res => {
                    setTimeout(function () {uni.hideLoading();}, 200)
                    this.getCartList()
                })
            },
            //勾选、取消勾选商品（点击商品）
            handleCheckSku(sku){
                console.log("=====handleCheckSku=====")
                uni.showLoading({title: '加载中',mask:true});
                const checked = sku.checked ? 0 : 1
                API_Trade.updateSkuChecked(sku.sku_id, checked).then(res => {
                    setTimeout(function () {uni.hideLoading();}, 200)
                    this.getCartList()
                })
            },
            //全选、取消全选
            handleCheckAll(){
                console.log("=====handleCheckAll=====")
                uni.showLoading({title: '加载中',mask:true});
                const checked = this.all_checked ? 0 : 1
                API_Trade.checkAll(checked).then(res => {
                    setTimeout(function () {uni.hideLoading();}, 200)
                    this.getCartList()
                })
            },
            //批量删除
            handleBatchDelete() {
                console.log("=====handleBatchDelete=====")
                const sku_ids = this.skuList.filter(item => item.checked).map(item => item.sku_id)
                let that = this
                uni.showModal({
                    title: '提示',
                    content: '确定要删除这个货品吗？',
                    confirmColor: '#ff5000',
                    success(res) {
                        if(res.confirm) {
                            API_Trade.deleteSkuItem(sku_ids).then(() => {
                                uni.showToast({ title: '删除成功' })
                                that.getCartList()
                            })
                        }
                    }
                })
            },
            //左滑点击删除
            handleDelete(sku_id) {
                console.log("=====handleDelete=====")
                let that = this
                uni.showModal({
                    title: '提示',
                    content: '确定要删除这个货品吗？',
                    confirmColor: '#ff5000',
                    success(res) {
                        if(res.confirm) {
                            API_Trade.deleteSkuItem(sku_id).then(() => {
                                uni.showToast({ title: '删除成功' })
                                // 为了公用组件销毁并重建
                                that.showSwipe = false
                                that.$nextTick(() => {
                                    that.showSwipe = true
                                })
                                that.getCartList()
                            })
                        }
                    }
                })
            },
            //左滑菜单-点击删除
            click(sku_id, index1) {
                console.log("=====click=====")
                this.handleDelete(sku_id);
            },
            //登录判断
            handleLogin() {
                console.log("=====handleLogin=====")
                this.judgeLogin(() => {},'force')
            },
        }
	}
</script>

<style lang="scss" scoped>
    /deep/ {
        .u-empty {
            padding-top: 200rpx !important;
        }
        .u-tag {
            font-size: 22rpx !important;
            padding: 8rpx 20rpx !important;
        }
        .u-icon-minus,.u-icon-plus {
            background-color: #fff !important;
        }
    }
    .cart-view {
        padding-bottom: 120rpx;
        .cart-list-view {
           .seller-view {
               background-color: #FFFFFF;
               border-radius: 20rpx;
               overflow: hidden;
               margin-top: 20rpx;
               .seller-item {
                   width: 100%;
                   margin: 20rpx;
                    .seller-checbox-view {
                        // width: 120rpx;
                        display: flex;
                        justify-content: center;
                    }
                    .seller-name-view {
                        padding-left: 25rpx;
                        font-size: 30rpx;
                        font-weight: 600;
                    }
               }
           }
        }

    }
    .cart-list {
        margin: 20rpx;
        border-radius: 20rpx;
        overflow: hidden;
        background-color: #FFFFFF;
        &.invalid .cart-item {
            filter: grayscale(1);
        }
        .error-message {
            padding-left: 17%;
            color: #ff5000;
        }
        .cart-item {
            width: 100%;
            background-color: #FFFFFF;
            .goods-checbox-view {
                line-height: 200rpx;
                display: flex;
                justify-content: center;
            };
            .goods-img-view {
                padding: 10rpx;
            };
            .goods-info-view {
                padding: 15rpx;
                padding-right: 20rpx;
                .goods-title {
                    min-height: 60rpx;
                }
                .goods-spec-view {
                    margin: 15rpx 0;
                    height: 28rpx;
                    .goods-spec {
                        color: #909399;
                        background-color: #f3f4f6;
                        padding: 0 5rpx;
                        font-size: 24rpx;
                    }
                }
                .promotion-view {
                    margin-top: 20rpx;
                }
                .act-view {
                    margin: 10rpx 0;
                    padding: 10rpx;
                    color: #909399;
                    background-color: #FDF3F3;
                    .act-item-cont {
                        margin-left: 20rpx;
                        font-size: 22rpx;
                    }
                }
            }
        }
    }

    .act-box-view {
        .title {
            font-weight: 600;
        }
    }

    .settlement {
        position: fixed;
        z-index: 99;
        bottom: 0;
        // #ifdef H5
        bottom: 100rpx;
        // #endif
        left: 0;
        display: flex;
        margin-top: 100rpx;
        border: solid 2rpx #f2f2f2;
        background-color: #ffffff;
        height: 100rpx;
        width: 100%;
        align-items: center;
        justify-content: space-between;
        padding: 0rpx 20rpx;
        -webkit-overflow-scrolling: touch;
        .del-btn {
            color: #ff5000;
            font-size: 24rpx;
            margin-left: 15rpx;
        }
        .cash-back {
            color: #7f828b;
        }
    }
    .go-login-btn {
        display: flex;
        justify-content: center;
        margin-top: 30rpx;
        .btn {
            background: #ff5000;
            color: #fff;
        }
    }
</style>
